<template>
	<!-- 交货单入库 -->
	<view class>
		<view class="card-wrapper">
			<view class="radius shadow shadow-lg bg-white padding-sm light bg-blue">
				<view class="flex flex-wrap">
					<view class="basis-xs">单据编号:</view>
					<view class="basis-xl text-black">{{ mainOrder.BILLNO }}</view>
				</view>

				<view class="flex flex-wrap margin-top" @tap="activeIndexM('1','GROUP')">
					<view class="basis-xs">发货集团:</view>
					<view class="basis-xl text-black solid-bottom position-r">
						<input class="wc-input" type="text" disabled v-model="mainOrder.GROUPNAME" placeholder="选择集团" />
						<view class="basis-xs text-right position-a down-arrow-btn">
							<text class="cuIcon-triangledownfill text-xxl text-bold"></text>
						</view>
					</view>
				</view>
				<view class="flex flex-wrap margin-top" @tap="activeIndexM(2,'BA_ORGANIZE')">
					<view class="basis-xs">发货单位:</view>
					<view class="basis-xl text-black solid-bottom position-r">
						<input class="wc-input" name="STORENAME" type="text" disabled v-model="mainOrder.ORGNAME"
							placeholder="选择发货单位" />
						<view class="basis-xs text-right position-a down-arrow-btn">
				  	<text class="cuIcon-triangledownfill text-xxl text-bold"></text>
						</view>
					</view>
				</view>
				<view class="flex flex-wrap margin-top" @tap="activeIndexM(0,'BA_DEPARTMENT')">
					<view class="basis-xs">发货部门:</view>
					<view class="basis-xl text-black solid-bottom position-r">
						<input class="wc-input" disabled  type="text" v-model="mainOrder.DEPTNAME"
							placeholder="选择部门" />
						<view class="basis-xs text-right position-a down-arrow-btn">
							<text class="cuIcon-triangledownfill text-xxl text-bold"></text>
						</view>
					</view>
				</view>
				
				<view class="flex flex-wrap margin-top" @tap="activeIndexM(2,'BD_CUSTOMER')">
					<view class="basis-xs">收货单位:</view>
					<view class="basis-xl text-black solid-bottom position-r">
						<input class="wc-input" name="STORENAME" type="text" disabled v-model="mainOrder.SUPPLYNAME"
							placeholder="选择收货单位" />
						<view class="basis-xs text-right position-a down-arrow-btn">
				  	<text class="cuIcon-triangledownfill text-xxl text-bold"></text>
						</view>
					</view>
				</view>
				
				<view class="flex flex-wrap margin-top" @tap="activeIndexM(0,'BA_USER')">
					<view class="basis-xs">申请人:</view>
					<view class="basis-xl text-black solid-bottom position-r">
						<input class="wc-input" name="APPLYER" type="text" disabled v-model="mainOrder.APPLYER"
							placeholder="选择申请人" />
						<view class="basis-xs text-right position-a down-arrow-btn">
				  	<text class="cuIcon-triangledownfill text-xxl text-bold"></text>
						</view>
					</view>
				</view>
				
				<!-- <view class="flex flex-wrap margin-top">
					<view class="basis-xs">申请人:</view>
					<view class="basis-xl text-black">{{ mainOrder.APPLYER || mainOrder.PURER }}</view>
				</view> -->

				<view class="flex flex-wrap margin-top">
					<view class="basis-xs">
						仓库
						<span class="text-red">*</span>
					</view>
					<view class="basis-xl text-black position-r solid-bottom"
						:class="isActiveStore? 'solid-bottom-blue' :'' ">
						<input class="wc-input" style="width: 60%;" name="STORENAME" type="text"
							@tap="seachEvent('BD_STORE','1')" :value="mainOrder.STORENAME" disabled
							placeholder="请选择或扫码" />
						<view class="basis-xs text-right position-a scan-btn" @tap="handelScan(1,'M')">
							<text class="cuIcon-scan text-xxl text-bold"></text>
						</view>
					</view>
				</view>

				<!-- <view class="flex flex-wrap margin-top">
					<view class="basis-xs">入库类型:</view>
					<view class="basis-xl text-black solid-bottom">
						<picker @change="bindPickerChangeWare" :value="mainOrder.INTYPE_index || 0" :range="wareType"
							:disabled="mainOrder.isCheckWareType" range-key="ItemName" class="picker-wrap">
							<view>{{ wareType[mainOrder.INTYPE_index].ItemName || '请选择' }}</view>
							<text class="dicon diconxiangxiazhankai position-a down-arrow"></text>
						</picker>
					</view>
				</view> -->

				<view class="flex flex-wrap margin-top">
					<view class="basis-xs">备注:</view>
					<view class="basis-xl text-black solid-bottom" :class="isActiveNote? 'solid-bottom-blue' :'' ">
						<input class="wc-input" type="text" v-model="VMEMO" placeholder="请输入备注" />
					</view>
				</view>


			</view>
			<!-- 物资子表 -->

			<view class="radius shadow shadow-lg bg-white padding-sm margin-top sub-table"
				v-for="(item,index) in planList" :key="index">
				<view class="flex flex-wrap">
					<view class="basis-xs">物资单号</view>
					<!-- <view class="basis-xl text-black">{{ item[mid] }}</view> -->
					<view class="basis-xl text-black">{{ item.PK_MATERIAL }}</view>
				</view>
				<view class="flex flex-wrap margin-top">
					<view class="basis-xs">物资名称</view>
					<view class="basis-xl text-black">
						{{ item.MATERIALNAME }}
					</view>
				</view>
				<view class="flex flex-wrap margin-top">
					<view class="basis-xs">物资规格</view>
					<view class="basis-xl text-black">{{ item.MATSPEC }}</view>
				</view>

				<view class="flex flex-wrap margin-top">
					<view class="basis-xs">申请数量</view>
					<view class="basis-xl text-black">{{ item.NNUMSQ }}/{{ item.UNIT || item.UNITNAME }}</view>
				</view>

				<view class="flex flex-wrap margin-top ">
					<view class="basis-xs">入库数量<text class="text-red">*</text></view>
					<view class="basis-xl solid-bottom sub-table-input">
						<input class="wc-input" v-model="item.NNUM" type="number" placeholder="请输入" />
					</view>
				</view>

				<!-- <view class="flex flex-wrap margin-top ">
					<view class="basis-xs">税率</view>
					<view class="basis-xl solid-bottom sub-table-input">
						<picker @change="bindPickerChange($event,index)" :value="item.VBDEF20 || 0" :range="taxRate"
							range-key="ItemName" class="picker-wrap">
							<view>{{ item.VBDEF20? taxRate[item.VBDEF20].ItemName : '请选择' }}</view>
							<text class="dicon diconxiangxiazhankai position-a down-arrow"></text>
						</picker>
					</view>
				</view> -->

				<view class="flex flex-wrap margin-top">
					<view class="basis-xs">
						货位
						<span class="text-red">*</span>
					</view>
					<view class="basis-xl text-black position-r solid-bottom"
						:class="isActiveStore? 'solid-bottom-blue' :'' ">
						<input class="wc-input" disabled style="width: 60%;" name="STATIONNAME" type="text"
							@tap="seachEvent('BD_RACK','0',index,mainOrder.PK_STORE)" placeholder="请选择或扫码"
							:value="item.STATIONNAME" />
						<view class="basis-xs text-right position-a scan-btn" @tap="handelScan('2',index)">
							<text class="cuIcon-scan text-xxl text-bold"></text>
						</view>
					</view>
				</view>

				<view class="flex flex-wrap margin-top">
					<view class="basis-xs">生产日期</view>
					<view class="basis-xl text-black solid-bottom" @click="dateEvent('FACTORYDATE',index)">
						{{ item.FACTORYDATE }}</view>
				</view>

				<view class="flex flex-wrap margin-top">
					<view class="basis-xs">保质期</view>
					<view class="basis-xl text-black solid-bottom">
						<input class="wc-input" v-model="item.EXPDATE" type="text" value="item.EXPDATE"
							placeholder="请输入到货量" />
					</view>
				</view>

				<view class="flex flex-wrap margin-top">
					<view class="basis-xs">入库日期</view>
					<view class="basis-xl text-black" @click="dateEvent('INSTOCKDATE',index)">{{ item.INSTOCKDATE }}
					</view>
				</view>

				<view class="flex flex-wrap margin-top">
					<view class="basis-xs">备注</view>
					<view class="basis-xl text-black solid-bottom">
						<input class="wc-input" v-model="item.VMEMO" type="text" value="item.EXPDATE"
							placeholder="请输入备注" />
					</view>
				</view>

				<!-- <view class="flex flex-wrap margin-top">
					<view class="basis-xs">
						图片上传
						<span class="text-red">*</span>
					</view>
					<view class="basis-xl text-black position-r solid-bottom">
						<image :src="item.INPHOTO" mode class="input-img" @tap="previewImage(index)" />
						<view class="basis-xs text-right position-a scan-btn" @click="updateImg(index)">
							<text class="cuIcon-upload text-xxl text-bold"></text>
						</view>
					</view>
				</view> -->

				<view class="flex-just-center margin-top btn-wrap">
					<!-- <button class="cu-btn round lines-blue" @click.stop="openShowModal">打印状态</button> -->

					<button class="cu-btn round lines-blue" @click.stop="submitPrint(item)">提交入库</button>
				</view>

			</view>
		</view>

		<!-- <view class="operation">
			<view class="operation-button border-right" @click="finishSubmit">
				完成入库
			</view>
		</view> -->
		<modal title="请输入打印数量" :isShow="isShowModal" @cancelModal="cancelModal" @okModal="okModal"></modal>
		<w-picker mode="dateTime" startYear="2000" endYear="2050" step="1" :defaultVal="[1,1,1,1,2,5]" :current="true"
			@confirm="onConfirm" ref="dateTime" themeColor="#f00"></w-picker>
	</view>

</template>
<script>
	import {
		mapState,
		mapMutations
	} from "vuex";
	import wPicker from "@/components/w-picker/w-picker.vue";
	import api from "@/common/api.js";
	import utils from "@/common/util.js";
	import modal from "@/components/modal/modal_print.vue";
	const plug = uni.requireNativePlugin('Html5app-Gprinter');
	let query = {
		category: "ST_INAPPLY",
		page: 1,
		rows: "50",
		sidx: "",
		sord: "",
		queryJson: {},
		userId: "",
		account: "admin"
	};
	let _self, dateTimekey, activeIndex, VMEMO, BILLFROM, ajaxUrl, activeType,
		qrcodeData = {
			number: 1
		};
	export default {
		computed: mapState(["userInfo", "taxRate", "wareType"]),
		data() {
			return {
				bstype: "",
				mainOrder: {},
				planList: [],
				isShowModal: false,
				isActiveNote: false,
				isActiveStore: false,
				mid: "",
				today: utils.getToDay(),
				dateTimekey: "",
				VMEMO: "",
				activeIndex: "",
				label01: "单号" // 主表的第一个label
			};
		},
		components: {
			wPicker,
			modal
		},
		onLoad(p) {
			// console.log(p);
			// console.log(this.userInfo);
			_self = this;
			this.bstype = p.t;
			query.userId = _self.userInfo.UserId;
			query.account = _self.userInfo.Account;
			query.category = p.dbt;
			let abc = JSON.parse(decodeURIComponent(p.item));
			// abc.INTYPE = this.wareType[0].ItemValue // 默认的入库类型
			// abc.INTYPE_index = 0
			abc.isCheckWareType = false // 入库类型 是否可选
			abc.PK_DEPT = '' // abc.PK_DEPT || _self.userInfo.PK_DEPT
			abc.DEPTNAME = '' // abc.DEPTNAME || _self.userInfo.DEPTNAME

			abc.PK_STORE = "";
			abc.STORENAME = "";
			
			abc.PK_APPLYER = "";
			abc.APPLYER = "";
			
			abc.PK_SUPPLY = "";
			abc.SUPPLYNAME = "";
			
			_self.mainOrder = abc;
			ajaxUrl = api.apiPublic.saveInStore;
			// console.log(abc);
			// let queryJsonID = "PK_" + query.category.split("_")[1];
			query.queryJson.PK_CEMENTOUT = p.id;
			// query.queryJson.ISFINISH  = 0;
			query.FRBILLNO = p.id;
			_self.getDetail();
			this.listenOnce()
		},

		onShow() {
			uni.$on("getSelectItem", function(data) {
				switch (activeType) {
					case "GROUP":
						_self.mainOrder.GROUPNAME = data.FullName;
						_self.mainOrder.PK_GROUP = data.OrganizeId;
						break;
					case "BA_ORGANIZE":
						_self.mainOrder.ORGNAME = data.FullName;
						_self.mainOrder.PK_ORG = data.OrganizeId;
						break;
					case "BA_DEPARTMENT":
						_self.mainOrder.DEPTNAME = data.FullName;
						_self.mainOrder.PK_DEPT = data.DepartmentId;
						break;
					case "BD_CUSTOMER":
						_self.mainOrder.SUPPLYNAME = data.VNAME;
						_self.mainOrder.PK_SUPPLY = data.BILLNO;
						break;
					case "BA_USER":
						_self.mainOrder.APPLYER = data.RealName;
						_self.mainOrder.PK_APPLYER = data.UserId;
						break;
					case "BD_STORE": // 仓库
						if (_self.activeSub) {
							_self.checkData[_self.activeLineIndex].PK_STORE = data.BILLNO;
							_self.checkData[_self.activeLineIndex].STORENAME = data.VNAME;
						} else {
							_self.mainOrder.PK_STORE = data.BILLNO;
							_self.mainOrder.STORENAME = data.VNAME;
						}
						break;
					case "BD_RACK": // 货位
						if (_self.activeSub) {
							_self.checkData[_self.activeLineIndex].STATIONNAME = data.FULLVNAME;
							_self.checkData[_self.activeLineIndex].PK_STATION = data.BILLNO;
						}
						break;
					default:
						break;
				}
				console.log(activeType,_self.mainOrder);
			});
		},

		methods: {
			// 执行监听 $once
			listenOnce() {
				uni.$on("getSelectItem", function(data) {
					// console.log(data);
					// console.log(activeType);
					switch (activeType) {
						case "MSTORE": // 主表仓库
							_self.mainOrder.PK_STORE = data.BILLNO;
							_self.mainOrder.STORENAME = data.VNAME;
							break;
						case "BA_DEPARTMENT": // 主表部门选择
							_self.mainOrder.DEPTNAME = data.FullName;
							_self.mainOrder.PK_DEPT = data.OrganizeId;
							break;
						case "BD_STORE": // 仓库子
							_self.planList[activeIndex].PK_STORE = data.BILLNO;
							_self.planList[activeIndex].STORENAME = data.VNAME;
							break;
						case "BD_RACK": // 货位子
							_self.planList[activeIndex].STATIONNAME = data.FULLVNAME;
							_self.planList[activeIndex].PK_STATION = data.BILLNO;
							break;
						default:
							break;
					}
				});
			},

			activeIndexM(i, t) {
				_self.activeLineIndex = i;
				activeType = t;
				let queryParames = "",
					pk_my_org = "";
				if (t == "BA_DEPARTMENT") {
					pk_my_org = this.mainOrder.PK_ORG;
				} else if (t == "BA_ORGANIZE") {
					pk_my_org = this.mainOrder.PK_GROUP;
				}

				uni.navigateTo({
					url: "/pages/public/search?t=" +
						t +
						"&organizeId=" +
						pk_my_org +
						"&queryjson=" +
						queryParames
				});
			},

			seachEvent(t, isMainTB, i, store) {
				// console.log(t,isMainTB,i,store);
				activeType = isMainTB == 1 ? "MSTORE" : t;
				activeIndex = i; // 激活的子表下标
				let queryParames = "",
					PK_ORG_S = '';
				if (t == "BD_RACK" && !this.mainOrder.PK_STORE) {
					return utils.tips("请先选择仓库");
				} else if (t == "BD_RACK") {
					queryParames = JSON.stringify({
						PK_STORE: this.mainOrder.PK_STORE
					});
				} else if (t == "BA_DEPARTMENT") {
					PK_ORG_S = this.mainOrder.PK_ORG
				}

				uni.navigateTo({
					url: "/pages/public/search?t=" + t + "&queryjson=" + queryParames + '&PK_ORG=' + PK_ORG_S
				});
			},
			onConfirm(val) {
				this.planList[activeIndex][dateTimekey] = val.result;
			},
			dateEvent(id, index) {
				dateTimekey = id;
				activeIndex = index;
				this.$refs.dateTime.show();
			},
			bindPickerChangeWare: function(e, i) {
				let val = e.target.value;
				_self.mainOrder.INTYPE = this.wareType[val].ItemValue
				_self.mainOrder.INTYPE_index = val
			},

			bindPickerChange: function(e, i) {
				let val = e.target.value;
				_self.activeIndex = i;
				_self.planList[_self.activeIndex].VBDEF20 = val;
				_self.planList[_self.activeIndex].NTAXRATE = _self.taxRate[val].ItemValue;
			},

			handelScan(id, index) {
				let URL = api.apiPublic.ScanCode;
				let type = {
					1: '仓库',
					2: '货位'
				};
				// console.log(id, index);
				this.$utils.Scan(URL, data => {
					console.log(data);
					if (id == 1 && data.PK_STORE) { // 获取主表的仓库
						_self.mainOrder.PK_STORE = data.PK_STORE;
						_self.mainOrder.STORENAME = data.STORENAME;
					} else if (id == 2 && data.PK_STATION) {
						_self.planList[index].STATIONNAME = data.STATIONNAME;
						_self.planList[index].PK_STATION = data.PK_STATION;
						if (!_self.mainOrder.PK_STORE) { // 如果仓库未选择时扫码货位带上仓库
							_self.mainOrder.PK_STORE = data.PK_STORE;
							_self.mainOrder.STORENAME = data.STORENAME;
						}
					} else {
						this.$utils.tips('未获取到二维码中的' + type[id])
					}

				});
			},

			getDetail() {
				let URL = '/api/APPCommon/GetSaleCommitDetailsList';
				// console.log(query);
				this.axios({
					url: URL,
					data: query,
					isLoading: 1
				}).then(res => {
					// console.log(res);
					let array = res.Result.rows.map(item => {
						item.FACTORYDATE = "";
						item.EXPDATE = "180";
						item.INSTOCKDATE = utils.getToDay();
						item.STORENAME = "";
						item.PK_STORE = "";
						item.STATIONNAME = "";
						item.PK_STATION = "";
						item.INPHOTO = "";
						item.NNUM = item.WNUM || item.NNUMSQ || item.ORDERNUM || '';
						item.NNUMSQ = item.ORDERNUM || item.WNUM || ''
						// item.VBDEF20 = 0
						// item.NTAXRATE = _self.taxRate[0].ItemValue
						for (var i = 0; i < _self.taxRate.length; i++) {
							let itemT = _self.taxRate[i];
							if (itemT.ItemValue == item.NTAXRATE) {
								item.VBDEF20 = i;
								item.NTAXRATE = itemT.ItemValue;
							}
						}
						return item;
					});
					_self.planList = array;
				}).catch(err => {
					console.log(err);
				})
			},
			submitPrint(item) {
				if (!item.NNUM) {
					return this.$utils.tips("请输入入库数量");
				} else if (!item.PK_STATION) {
					return this.$utils.tips("货位不能为空");
				} 
				
				// else if (!item.INPHOTO) {
				// 	return this.$utils.tips("请上传入库图片");
				// }
				let data = {
					FRBILLNO: _self.mainOrder.BILLNO,
					BILLFROM: 4 ,
					SUPPLYNAME : _self.mainOrder.SUPPLYNAME,//
					PK_SUPPLY: _self.mainOrder.PK_SUPPLY, // 客户 收货单位
					PK_STORE: _self.mainOrder.PK_STORE, //CKGL20190802000001
					STORENAME: _self.mainOrder.STORENAME, // 测试仓库
					ORGNAME: _self.mainOrder.ORGNAME,
					PK_ORG: _self.mainOrder.PK_ORG,
					DEPTNAME: _self.mainOrder.DEPTNAME,
					PK_DEPT: _self.mainOrder.PK_DEPT,
					APPLYER: _self.mainOrder.APPLYER,
					PK_APPLYER: _self.mainOrder.PK_APPLYER,
					PK_GROUP: _self.mainOrder.PK_GROUP,
					GROUPNAME: _self.mainOrder.GROUPNAME,
					
					VMEMO: _self.VMEMO,
					userId: _self.userInfo.USERID,
					account: _self.userInfo.ACCOUNT,
					Detail: JSON.stringify([item])
				};
				// console.log(JSON.stringify(data));
				// "TYPE:3|" + objs[i].PK_ORG + "|" + objs[i].PK_STORE + "|" + objs[i].PK_STATION + "|" + objs[i].INBARCODE;
				let TNT = `TYPE:3|${item.PK_ORG}|${data.PK_STORE}|${item.PK_STATION}|`;
				qrcodeData = {
					name: item.MATERIALNAME,
					type: item.MATSPEC,
					bcode: '',
					qcode: TNT,
					number: 1
				}
				// return ;
				// console.log(qrcode);
				let URL = '/api/APPCommon/SaveTon_PurInStore';
				this.axios({
					url: URL,
					data: data,
					isLoading: 1
				}).then(res => {
					console.log(12, res);
					let {
						Message,
						Result
					} = res;
					qrcodeData.bcode = Result.DTL[0].BARCODE
					qrcodeData.qcode += qrcodeData.bcode
					_self.isShowModal = true;
					// _self.openShowModal()
				})
			},
			// 打印判断

			// 图片上传
			updateImg(i) {
				_self.activeIndex = i;
				_self.$utils.uploadImg(function(e) {
					_self.planList[_self.activeIndex].INPHOTO = e;
					// console.log(_self.planList[_self.activeIndex].INPHOTO);
				});
			},
			// 图片查看
			previewImage(i) {
				let imglist = this.planList[i].INPHOTO;
				_self.$utils.previewImage(imglist);
			},

			// 控制输入数量的对话框
			cancelModal() {
				this.isShowModal = false;
			},
			okModal(val) {
				qrcodeData.number = val
				this.printerLable(qrcodeData)
			},

			// 打印标签
			printerLable(data) {
				plug.printer({
					"TSC": _self.$utils.LableSet(data)
				}, ret => {
					// _this.tip=JSON.stringify(ret);
					if (ret.state == 1) {
						_self.$utils.tips('提交成功，打印失败！')
						_self.getDetail();
					} else if (ret.state == 2) {
						_self.$utils.tips('已完成打印')
						_self.getDetail();
					}
					// console.log(JSON.stringify(ret));
				});
			},
			//查询打印机状态
			state() {
				let _this = this;
				plug.state({}, ret => {
					_this.tip = JSON.stringify(ret);
					console.log(_this.tip);
				});
			},

			// 完成入库提交
			finishSubmit() {
				console.log(query);
				let saveData = {
					FRBILLNO: query.FRBILLNO,
					userId: query.userId,
					account: query.account,
					TYPE: 'ST_PURINSTORE'
				}
				// console.log(saveData);
				let URL = '/api/APPCommon/FinishBillSubmit';
				this.axios({
					url: URL,
					data: saveData,
					isLoading: 1
				}).then(res => {
					let {
						Message,
						Result
					} = res;
					_self.$utils.tips('提交成功')
					setTimeout(r => {
						uni.navigateBack({})
					}, 1600)
				})
			}

		}
	};
</script>

<style scoped lang="scss">
	.card-wrapper {
		padding: 26upx;
		padding-bottom: 100rpx;
	}

	.line-height-30 {
		line-height: 24px !important;
	}

	

	.sub-table-input {
		margin-top: 10upx;
	}
</style>
